package com.dxy.shardingjdbc.algorithm;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description 告警表分库复核算法
 * @Author dangxianyue
 * @Date 2023/2/8 13:54
 */
public class AlarmSubDatabaseComplexAlgorithm implements ComplexKeysShardingAlgorithm {

    //id列名
    private static final String COLUMN_ID = "id";

    //告警时间列名
    private static final String COLUMN_ALARM_TIME = "alarm_time";

    /**
     * 分库算法逻辑
     * @param availableTargetNames 物理库列表，alarm-2021、alarm-2022、alarm-2023、alarm-2024
     * @param shardingValue 分片键的值，id、alarm_time
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection availableTargetNames, ComplexKeysShardingValue shardingValue) {
        System.out.println("subDatabase:\navailableTargetNames: " + JSON.toJSONString(availableTargetNames) + "\nshardingValue: " + JSON.toJSONString(shardingValue));

        // 获取id
        Collection ids = (Collection) shardingValue.getColumnNameAndShardingValuesMap().getOrDefault(COLUMN_ID, new ArrayList<>(1));

        // 获取告警时间
        Collection alarmTimes = (Collection) shardingValue.getColumnNameAndShardingValuesMap().getOrDefault(COLUMN_ALARM_TIME, new ArrayList<>(1));

        // 整合id和告警时间
        List<String> list = new ArrayList<>();
        // 告警id开头包含6位日期：yyMMdd
        // 当前为20xx年
        ids.forEach(id -> list.add("20" + id.toString().substring(0, 2)));
        alarmTimes.forEach(alarmTime -> list.add(LocalDateTimeUtil.format((LocalDateTime) alarmTime, "yyyy")));

        List<String> dbList = list.stream()
                //去重
                .distinct()
                //匹配过滤得到正确的数据库
                .map(dbSuffix -> availableTargetNames.stream().filter(dbName ->
                        dbName.toString().endsWith(dbSuffix)).findFirst().orElse(null))
                .filter(Objects::nonNull)
                //转化为string
                .map(String::valueOf)
                .collect(Collectors.toList());
        System.out.println("dbList: " + JSON.toJSONString(dbList));
        return dbList;
    }

}
